const Redis = require('ioredis')

module.exports = ({ config, logger }) => {
  if (config.get('useRedis') === 0) return null

  const { host, port } = config.get('redis')
  const redis = new Redis(host, port, {
    showFriendlyErrorStack: true,
    // lazyConnect: true,
  })

  redis.on('connect', () => {
    logger.info(`[Redis Client]  redis://${host}:${port} 链接成功`)
  })

  redis.on('error', (e) => {
    logger.error(`[Redis Client]  redis://${host}:${port} 链接失败`)
    logger.error(e)
  })

  return {
    redis,
    cacheHelper: (fn, key, time = 60) => {
      return async (...args) => {
        const redisData = await redis.get(key)
        const cacheData = redisData ? JSON.parse(redisData) : null
        if (cacheData) return cacheData
        const data = await fn(...args)
        redis.set(key, JSON.stringify(data), 'EX', time)
        return data
      }
    },
  }
}
